<?php

namespace Common\Model;
use Org\Util\SFile;

class UserGroupModel extends AllModel{
    
    /**
     * 获取权限组详情
     * @param type $id
     * @param type $cache
     * @return type
     */
    public function get_info($id = 0, $cache = false) {
        if($id == 1){
            return array('name' => '超级权限组','content'=>'');
        } else if($id == 0){
            return array('name' => '无权限/普通用户','content'=>'');
        }
        return parent::get_info($id, $cache);
    }

    private $temp = array();
    /**
     * 获取权限组详情
     * @param intval $gid 要获取的权限组
     * @return array 获取的权限详情
     *      return array(
     *          'Home/Index/index' => array(
     *              'key' => 'Home/Index/index',
     *              'info' => 1
     *          )
     *          ......
     *      )
     */
    public function get_group_content($gid = 0,$leader = false){
        if($gid <= 1){
            return array();
        }
        $info = parent::get_info($gid);
        $this->temp[] = $info['content'];
        $this->get_child_group($info['id'],$info['type']);
        $info = explode(',', implode(',', $this->temp));
        $r_info = array();
        foreach($info as $v){
            if(!empty($v)){
                $r_info[$v] = array(
                    'key' => $v,
                    'info' => $leader > 0 ? 2 : 1,
                );
            }
        }
        return $r_info;
    }
    
    /**
     * 递归获取子权限组详情
     *      该函数使用$this->temp数组来递归添加子权限组数据
     * 
     * @param intval $fid 父权限组ID
     * @param intval $type 权限类型
     * @return none
     */
    public function get_child_group($fid = 0,$type = 1){
        if($fid <= 0){
            return '';
        }
        $info = $this->where(array('fix_id'=>$fid,'type' => $type))->cache(TRUE)->select();
        foreach($info as $v){
            $this->temp[] = $v['content'];
            $this->get_child_group($v['id'],$type);
        }
    }
    
    /**
     * 创建权限组操作
     * 
     * @param type $post
     * @return boolean
     */
    public function create_group($post = array()){
        $id = $this->create_info($post);
        (new SFile())->rm_dirs(RUNTIME_PATH);
        if($id){
            (new LogModel())->create_oth_log($id,'user_group');
            return $id;
        }
        return FALSE;
    }
    
    /**
     * 获取权限组类型列表
     * 
     * @param type $id 类型id
     * @return type
     */
    public function getListGroup($id = 0){
        $list_ = array();
        foreach (get_config('GroupType') as $k => $v){
            $list_[$k] = $this->where(['type'=>$k])->cache(TRUE)->getList(0,999);
        }
        if($id == 0){
            return $list_;
        }
        return $list_[$id];
    }
}